package com.ash.security.config;

import com.ash.security.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfig {


    @Autowired
    private MyAccessDeniedHandler myAccessDeniedHandler;

    /**
     * 指定密码加密的方法
     *
     * @return
     */
    @Bean
    public BCryptPasswordEncoder getPasswordEncode() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        //表单提交
        http.formLogin()
                //自定义用户名和密码参数
                .usernameParameter("username123")
                .passwordParameter("password123")
                //自定义登录页面
                .loginPage("/login.html")
                //必须和表单提交的接口一样，执行自定义登录逻辑
                .loginProcessingUrl("/login")
                //自定义登录成功处理器
                .successHandler(new LoginSuccessHandler("/main.html"))
                //自定义登录失败处理器
                .failureHandler(new LoginFailHandler("/error.html"));

        //授权
        http.authorizeRequests()
                //放行/login.html,不需要授权
                .antMatchers("/login.html").permitAll()
                //放行/error.html，不需要授权
                .antMatchers("/error.html").permitAll()
                //基于权限判断
//                .antMatchers("/main1.html").hasAuthority("permission2")
                //所有请求必须认证
                .anyRequest().authenticated();

        //异常处理器
        http.exceptionHandling().accessDeniedHandler(myAccessDeniedHandler);
//登出
        http.logout()
                //登出接口,与表单访问接口一致
                .logoutUrl("/signLogout")
                //登出处理器
                .addLogoutHandler(new MyLogoutHandler())
                //登出成功后跳转的页面
                .logoutSuccessHandler(new MyLogoutSuccessHandler("/login.html"));
        //关闭csrf防护
        http.csrf().disable();

        return http.build();
    }

    /**
     * 放行静态资源,css,js,images
     *
     * @throws Exception
     */
    public WebSecurityCustomizer webSecurityCustomizer() throws Exception {
        return web -> web.ignoring().antMatchers("/css/**", "/js/**")
                .antMatchers("/**/*.png");
    }

}
